package com.neusoft.elmboot.util;

import cn.hutool.core.util.StrUtil;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.neusoft.elmboot.util.Constants;
import com.neusoft.elmboot.mapper.BusinessMapper;
import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.util.ServiceException;
import com.neusoft.elmboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends InterceptorRegistry implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    
    @Autowired
    private BusinessMapper businessMapper;
    
    String key  = "woniucsdnvip8888";

    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object object) throws Exception{

        //获取token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
       
        token=AESUtils.decrypt(token, key);
        
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
        	setResponse(httpServletResponse, Constants.CODE_401, "没有token，重新登陆");
            return false;
        }

        //获取token的userid
        String Id;
        String type;
        try {
            //解密获取
            Id = JWT.decode(token).getAudience().get(0); //得到token中的userid载荷
            type =JWT.decode(token).getClaim("type").asString();;
        } catch (JWTDecodeException j) {
        	setResponse(httpServletResponse, Constants.CODE_401, "没有token，重新登陆");
            return false;
        }

        //根据userid查询数据库
       
       
        
        if (type.equals("user")) {
        	User user = userService.getEntireUserById(Id);
        	if(user == null){
        		setResponse(httpServletResponse, Constants.CODE_401, "没有token，重新登陆");
                return false;
        	}

        	// 用户密码加签验证 token
        	JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        	try {
        		jwtVerifier.verify(token);
        	} catch (JWTVerificationException e) {
        		setResponse(httpServletResponse, Constants.CODE_401, "没有token，重新登陆");
                return false;
        	}
        }
        
        else if (type.equals("business")) {
        	//System.out.println("!");
        	Business business=businessMapper.getEntireBusinessById(Id);
        	if(business == null){
        		System.out.println("!");
        		setResponse(httpServletResponse, Constants.CODE_401, "没有token，重新登陆");
                return false;
        	}

        	// 用户密码加签验证 token
        	JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(business.getPassword())).build();
        	try {
        		jwtVerifier.verify(token);
        	} catch (JWTVerificationException e) {
        		
        		setResponse(httpServletResponse, Constants.CODE_401, "没有token，重新登陆");
                return false;
        	}
        }

        return true;
    }
    private void setResponse(HttpServletResponse response, int code, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(code);
        response.getWriter().write("{\"code\":" + code + ",\"message\":\"" + message + "\"}");
    }
}


 //加密

 //解密
